/*
 * Copyright 2014 http://Bither.net
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.testjpg;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.testjpg.util.FileSizeUtil;
import com.example.testjpg.util.ImageUtil;
import com.example.testjpg.util.PathUtil;

import net.bither.util.NativeUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import me.nereo.multi_image_selector.MultiImageSelectorActivity;


public class MainActivity extends Activity {
    private final static int QUALITY = 50;
    private final static int REQUEST_CODE_XITONG = 0x1;
    private final static int REQUEST_CODE_THIRD = 0x2;
    private final static int REQUEST_CODE_CROP = 0x3;
    private ImageView image1, image2;
    private TextView text1/*, text2*/;
    private LinearLayout container;
    private String pictureSourcePath;//源文件路径

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        image1 = (ImageView) findViewById(R.id.image1);
        image2 = (ImageView) findViewById(R.id.image2);
        text1 = (TextView) findViewById(R.id.text1);
        //text2 = (TextView) findViewById(R.id.text2);
        container = (LinearLayout) findViewById(R.id.container);
        testJpeg();
    }

    /**
     * 第三方选图
     *
     * @param view
     */
    public void diSanFangXuanTu(View view) {
        Intent intent = new Intent(this, MultiImageSelectorActivity.class);
        // whether show camera
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
        // max select image amount
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 9);
        // select mode (MultiImageSelectorActivity.MODE_SINGLE OR MultiImageSelectorActivity.MODE_MULTI)
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
        // default select images (support array list)
        // intent.putStringArrayListExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, defaultDataArray);
        startActivityForResult(intent, REQUEST_CODE_THIRD);
    }

    /**
     * 调用系统图册
     *
     * @param view
     */
    public void xiTongXuanTu(View view) {
        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
        startActivityForResult(intent, REQUEST_CODE_XITONG);
    }

    /**
     * 选图截图
     *
     * @param view
     */
    public void xuanTuJieTu(View view) {
        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
        startActivityForResult(intent, REQUEST_CODE_CROP);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_XITONG && resultCode == RESULT_OK && null != data) {
            Uri uri = data.getData();
            pictureSourcePath = PathUtil.getPath(this, uri);
            new Thread(new Runnable() {
                public void run() {
                    //Bitmap afterDecoder;
                    //afterDecoder = decoderImage(pictureSourcePath).bitmap;
                    Message msg = mHandler.obtainMessage();
                    //msg.obj = afterDecoder;
                    msg.obj = decoderImage(pictureSourcePath);
                    msg.what = 2;
                    mHandler.sendMessage(msg);

                }
            }).start();
        } else if (requestCode == REQUEST_CODE_THIRD && resultCode == RESULT_OK) {
            container.removeAllViews();
            final List<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
            new Thread(new Runnable() {
                public void run() {
                    Bitmap afterDecoder;
                    for (String item : path) {
                        //afterDecoder = getImage(decoderImage(item));
                        afterDecoder = decoderImage(item).bitmap;
                        Message msg = mHandler.obtainMessage();
                        msg.what = 1;
                        msg.obj = afterDecoder;
                        mHandler.sendMessage(msg);
                    }
                }
            }).start();
        } else if (requestCode == REQUEST_CODE_CROP && resultCode == RESULT_OK && null != data) {
            Uri uri = data.getData();
            String picturePath = PathUtil.getPath(this, uri);
            Intent intent = new Intent(this, CropActivity.class);
            intent.putExtra(CropActivity.IMAGE_PATH, picturePath);
            startActivity(intent);
        }

    }

    /**
     * 压缩保存，并获取压缩后的文件路径
     *
     * @param path 源文件路径
     * @return 压缩质量
     */
    private /*String*/ DecodeResult decoderImage(String path) {
        double imageSourcesize = FileSizeUtil.getFileOrFilesSize(path, FileSizeUtil.SIZETYPE_KB);
        //
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        options.inSampleSize = NativeUtil.getRatioSize(options.outWidth, options.outHeight);
        options.inJustDecodeBounds = false;
        options.inDither = false;
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        Bitmap bit = BitmapFactory.decodeFile(path, options);
        //----------------------------------------------------
        //Bitmap bit = BitmapFactory.decodeFile(path);
        //----------------------------------------------------
        File dirFile = getExternalCacheDir();
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        File saveFile = new File(dirFile, "test.jpg");
        //NativeUtil.compressBitmap(bit, quality, saveFile.getAbsolutePath(), true);
        //DecodeResult result = new DecodeResult(saveFile.getAbsolutePath(), bit);
        DecodeResult result;
        if (imageSourcesize > 20) {//经测试，当源文件<20KB（左右），压缩后的文件反而更大，所以这里当文件>20KB 才压缩。这里20是个经验值
            NativeUtil.compressBitmap(bit, saveFile.getAbsolutePath());
            result = new DecodeResult(saveFile.getAbsolutePath(), bit);
        } else {
            result = new DecodeResult(path, bit);
        }
        return result;
//        if (bit != null && !bit.isRecycled()) {
//            bit.recycle();
//            bit = null;
//        }
//        return saveFile.getAbsolutePath();
    }

    /**
     * File转Bitmap,压缩后显示
     *
     * @param path
     * @return
     */
    private Bitmap getImage(String path) {
        Bitmap bmp = null;
        try {
            File file = new File(path);
            FileInputStream in = new FileInputStream(file);
            bmp = BitmapFactory.decodeStream(in);
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bmp;
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                Bitmap bitmap = (Bitmap) msg.obj;
                ImageView view = new ImageView(MainActivity.this);
                view.setScaleType(ImageView.ScaleType.FIT_XY);
                view.setAdjustViewBounds(true);
                view.setImageBitmap(bitmap);
                container.addView(view);
            } else if (msg.what == 2) {
                DecodeResult bitmapInfo = (DecodeResult) msg.obj;
                double imageSourcesize = FileSizeUtil.getFileOrFilesSize(pictureSourcePath, FileSizeUtil.SIZETYPE_KB);
                double imageCompressedSize = FileSizeUtil.getFileOrFilesSize(bitmapInfo.path, FileSizeUtil.SIZETYPE_KB);
                //float imageMemorySize = BigDecimalUtil.div(ImageUtil.getImageSize(bitmap), 1024, 2);
                float imageMemorySize = ImageUtil.getImageSize(bitmapInfo.bitmap);
                String textStr2 = "源文件大小=" + imageSourcesize + "KB； 压缩后大小=" + imageCompressedSize + "KB, 加载占用内存" + imageMemorySize + "KB";
                text1.setText(textStr2);
                image1.setImageBitmap(bitmapInfo.bitmap);
            }

        }
    };

    private void testJpeg() {
        new Thread(new Runnable() {
            public void run() {
                try {
                    int quality = 90;//original
                    quality = 50;//同学们可以与原生的压缩方法对比一下，同样设置成50效果如何
                    InputStream in = getResources().getAssets().open("test4.jpg");
                    Bitmap bit = BitmapFactory.decodeStream(in);
//                    String dirFile = Environment.getExternalStorageDirectory().toString();
                    File dirFile = getExternalCacheDir();
                    if (!dirFile.exists()) {
                        dirFile.mkdirs();
                    }
                    File originalFile = new File(dirFile, "original.jpg");
                    FileOutputStream fileOutputStream = new FileOutputStream(originalFile);
                    bit.compress(CompressFormat.JPEG, quality, fileOutputStream);
                    File jpegTrueFile = new File(dirFile, "jpegtrue.jpg");
                    File jpegFalseFile = new File(dirFile, "jpegfalse.jpg");
                    NativeUtil.compressBitmap(bit, quality,
                            jpegTrueFile.getAbsolutePath(), true);
                    NativeUtil.compressBitmap(bit, quality, jpegFalseFile.getAbsolutePath(), false);
                    //
                    fileOutputStream.close();
                    in.close();
                    if (bit != null && !bit.isRecycled()) {
                        bit.recycle();
                        bit = null;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }


    class DecodeResult {
        String path;
        Bitmap bitmap;

        DecodeResult(String path, Bitmap bitmap) {
            this.path = path;
            this.bitmap = bitmap;
        }
    }
}
